package com.wzdigit.wms.raw.service.mid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.client.response.basic.SkuBaseResponse;
import com.wzdigit.wms.basic.domain.mid.JobSyncErrorData;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.GdnDtlStatusEnum;
import com.wzdigit.wms.basic.enums.GdnHeaderStatusEnum;
import com.wzdigit.wms.basic.enums.GdnTypeEnum;
import com.wzdigit.wms.basic.enums.QaStatusEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.mid.JobSyncErrorDataMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnHeaderMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.raw.constant.SyncTypeConstant;
import com.wzdigit.wms.raw.domain.dto.HouseQaStatus;
import com.wzdigit.wms.raw.domain.dto.IfPoHeaderDto;
import com.wzdigit.wms.raw.domain.mid.IfPoDtl;
import com.wzdigit.wms.raw.domain.mid.IfPoHeader;
import com.wzdigit.wms.raw.domain.mid.PoDtl;
import com.wzdigit.wms.raw.domain.mid.PoHeader;
import com.wzdigit.wms.raw.exception.SyncException;
import com.wzdigit.wms.raw.mapper.mid.IfPoDtlMapper;
import com.wzdigit.wms.raw.mapper.mid.IfPoHeaderMapper;
import com.wzdigit.wms.raw.mapper.mid.PoDtlMapper;
import com.wzdigit.wms.raw.mapper.mid.PoHeaderMapper;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 接口中间表-采购订单 同步 采购订单
 * </p>
 *
 * @author chao shuai
 * @since 2021-06-10
 */
@Service
public class IfPoHeaderService {

    @Autowired
    private IfPoHeaderMapper ifPoHeaderMapper;

    @Autowired
    private IfPoDtlMapper ifPoDtlMapper;

    @Autowired
    private GdnHeaderMapper gdnHeaderMapper;

    @Autowired
    private GdnDtlMapper gdnDtlMapper;


    @Autowired
    private JobSyncErrorDataMapper jobSyncErrorDataMapper;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi  basicVendorApi;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SyncErrorDataService syncErrorDataService;

    @Autowired
    CodeMappingService codeMappingService;

    @Autowired
    MappingHouseService mappingHouseService ;

    @Autowired
    PoHeaderMapper poHeaderMapper ;
    @Autowired
    PoDtlMapper poDtlMapper;

    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;


    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;

    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;




    private final String syncType = SyncTypeConstant.IF_PO_TO_PO;

    public List<IfPoHeaderDto> selectSyncData() {
        ArrayList<IfPoHeaderDto> ifPoHeaderDtos = new ArrayList<>();
        QueryWrapper<IfPoHeader> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("Attribute10","1").or().isNull("Attribute10");
        List<IfPoHeader> selectSyncData = ifPoHeaderMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(selectSyncData)) {
            for (IfPoHeader ifPoHeader : selectSyncData) {
                IfPoHeaderDto ifPoHeaderDto = new IfPoHeaderDto();
                BeanUtil.copyNonNull(ifPoHeader, ifPoHeaderDto);
                List<IfPoDtl> ifSalesreturnDtls = ifPoDtlMapper.selectList(new QueryWrapper<>(
                        new IfPoDtl().setIfPoHeaderId(ifPoHeader.getIfPoHeaderId())
                ));
                ifPoHeaderDto.setIfPoDtlList(ifSalesreturnDtls);
                ifPoHeaderDtos.add(ifPoHeaderDto);
            }

        }
        return ifPoHeaderDtos;
    }




    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncDataGdn(IfPoHeaderDto data, boolean isSyncError) throws Exception {
        String werks = data.getIfPoDtlList().get(0).getWerks();//工厂
        String gdnNo = data.getEbeln(); //采购单号--》采购单号or退货单号
        //查询供应商信息//
        GdnHeader gdnHeader = new GdnHeader();
        VendorDTO vendor = basicVendorApi.getVendorByCode(data.getLifnr());
        if (vendor == null||vendor.getVendorId()==null) {
            //throw new SyncException(syncType, gdnNo, "供应商" + data.getLifnr() + "不存在");
        }else{
            gdnHeader.setConsigneeId(vendor.getVendorId().longValue());
            gdnHeader.setConsigneeName(vendor.getVendorName());
        }

        List<IfPoDtl> ifPoDtlList = data.getIfPoDtlList();


        //同步主表信息
        gdnHeader.setGdnNo(gdnNo);
        gdnHeader.setGdnType(GdnTypeEnum.D18.code);

        gdnHeader.setGdnCreateUser(data.getCreateUser());
        gdnHeader.setGdnCreateTime(data.getCreateTime());
        gdnHeader.setFactory(werks);
        gdnHeader.setShipDate(new Date());
//        DataItemDetailDTO dataItem = dataItemDetailApi.getDataItemDetailByPCodeAndName(DEFAULT_OWNER, DEFAULT_OWNER_NAME);
        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);


        gdnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0: Integer.valueOf(dataItem.getItemValue()));
        GdnHeader gdnHeaderRecord = gdnHeaderMapper.selectOne(new QueryWrapper<>(new GdnHeader().setGdnNo(gdnNo)));
        if (gdnHeaderRecord == null) {
            gdnHeader.setStatus(GdnHeaderStatusEnum.CREATE.getCode());//新建状态
            gdnHeader.setCreateUser("system");
            gdnHeader.setCreateTime(new Date());

            gdnHeaderMapper.insert(gdnHeader);
        } else {
            gdnHeader.setModifyTime(new Date());
            gdnHeader.setModifyUser("system");
            gdnHeader.setGdnHeaderId(gdnHeaderRecord.getGdnHeaderId());
            gdnHeaderMapper.updateById(gdnHeader);
        }
        //同步明细 内部自己生成行号
        //获取最大行号
        Integer maxLineNo = gdnDtlMapper.selectMaxLineId(gdnHeader.getGdnHeaderId());
        if(maxLineNo == null){
            maxLineNo = 1 ;
        }


        for (IfPoDtl ifPoDtl : ifPoDtlList) {
            GdnDtl gdnDtlRecord = gdnDtlMapper.selectOne(new QueryWrapper<>(new GdnDtl().setGdnHeaderId(gdnHeader.getGdnHeaderId()).setSourceShipNoticeItem(ifPoDtl.getEbelp())));
            //删除逻辑（明细表字段LOEKE写L）
            if("L".equals(ifPoDtl.getLoekz())){
                if(gdnDtlRecord==null){//查不到明细行 直接抛异常
                    throw new SyncException(syncType, gdnNo, "没有查询到要删除的明细行，行号【"+ifPoDtl.getEbelp()+"】,删除失败");
                }else{
                    poDtlMapper.deleteById(ifPoDtl.getIfPoDtlId());
                }
                continue;
            }

            //查询SKUID
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifPoDtl.getMatnr());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, gdnNo, "物料编码" + ifPoDtl.getMatnr() + "不存在");
            }
            //获取仓库
            if(ifPoDtl.getAttribute2() == null){
                throw new SyncException(syncType, gdnNo, "SAP仓库编码" + ifPoDtl.getAttribute2() + "为空");
            }
            HouseQaStatus houseQaStatus = mappingHouseService.getWmsHourseIdBySapHourseCode(ifPoDtl.getAttribute2());
            if(houseQaStatus==null){
                throw new SyncException(syncType, gdnNo, "SAP仓库编码" + ifPoDtl.getAttribute2() + "无法转换成WMS仓库");
            }


            GdnDtl gdnDtl = new GdnDtl();
            gdnDtl.setGdnHeaderId(gdnHeader.getGdnHeaderId());

            gdnDtl.setSkuId(sku.getSkuId());
            gdnDtl.setOrderQty(ifPoDtl.getMenge());
            gdnDtl.setGdnRef1(ifPoDtl.getRetpo());
            gdnDtl.setGdnRef2(ifPoDtl.getElikz());
            gdnDtl.setGdnRef3(ifPoDtl.getLoekz());
            gdnDtl.setUnit(sku.getBaseUnit());
            gdnDtl.setCreateTime(ifPoDtl.getCreateTime());
            gdnDtl.setCreateUser(ifPoDtl.getCreateUser());
            gdnDtl.setWhsId(houseQaStatus.getWhsId());
            gdnDtl.setSourceShipNoticeItem(ifPoDtl.getEbelp());
            gdnDtl.setQaStatus(houseQaStatus.getQaStatus());//检验状态待定

            if (gdnDtlRecord == null) {
                gdnDtl.setStatus(GdnDtlStatusEnum.CREATE.getCode());//新建状态

                gdnDtl.setGdnLineNo(maxLineNo++);//设置自定义行号
                try {
                    gdnDtlMapper.insert(gdnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, gdnNo, e.getMessage());
                }
            } else {
                gdnDtl.setModifyUser("system");
                gdnDtl.setModifyTime(new Date());
                gdnDtl.setGdnDtlId(gdnDtlRecord.getGdnDtlId());
                gdnDtl.setGdnLineNo(gdnDtlRecord.getGdnLineNo());//设置行号
                try {
                    gdnDtlMapper.updateById(gdnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, gdnNo, e.getMessage());
                }
            }
            int row = ifPoHeaderMapper.updateFlagById(data.getIfPoHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, gdnNo);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, gdnNo);
            }
        }

    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncDataPo(IfPoHeaderDto data, boolean isSyncError) throws Exception {
        String poNo = data.getEbeln(); //采购单号--》采购单号or退货单号
        //查询供应商信息
        VendorDTO vendor = basicVendorApi.getVendorByCode(data.getLifnr());
        if (vendor == null||vendor.getVendorId()==null) {
            throw new SyncException(syncType, poNo, "供应商" + data.getLifnr() + "不存在");
        }

        List<IfPoDtl> ifPoDtlList = data.getIfPoDtlList();

        PoHeader poHeader = new PoHeader();
        //同步主表信息

        
        poHeader.setPoNo(poNo);
        poHeader.setPoType(Long.parseLong(data.getZtype()));//待定
        poHeader.setVendorId(vendor.getVendorId().longValue());
        poHeader.setPurchaseOrg(data.getEkorg());
        poHeader.setCreateUser(data.getCreateUser());
        poHeader.setCreateTime(data.getCreateTime());




        PoHeader poHeaderRecord = poHeaderMapper.selectOne(new QueryWrapper<>(new PoHeader().setPoNo(poNo)));
        if (poHeaderRecord == null) {
            poHeader.setStatus(0L);//订单初始状态
            poHeaderMapper.insert(poHeader);
        } else {
            poHeader.setModifyTime(new Date());
            poHeader.setModifyUser("system");
            poHeader.setPoHeaderId(poHeaderRecord.getPoHeaderId());
            poHeaderMapper.updateById(poHeader);
        }
        //同步明细
        for (IfPoDtl ifPoDtl : ifPoDtlList) {
            PoDtl poDtlRecord = poDtlMapper.selectOne(new QueryWrapper<>(new PoDtl().setPoHeaderId(poHeader.getPoHeaderId()).setPoLineNo(ifPoDtl.getEbelp())));
            //删除逻辑（明细表字段LOEKE写L）
            if("L".equals(ifPoDtl.getLoekz())){
                if(poDtlRecord==null){//查不到明细行 直接抛异常
                    throw new SyncException(syncType, poNo, "没有查询到要删除的明细行，行号【"+ifPoDtl.getEbelp()+"】,删除失败");
                }else{
                    poDtlMapper.deleteById(ifPoDtl.getIfPoDtlId());
                }
                continue;//
            }
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifPoDtl.getMatnr());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, poNo, "物料编码" + ifPoDtl.getMatnr() + "不存在");
            }


            PoDtl poDtl = new PoDtl();
            poDtl.setPoHeaderId(poHeader.getPoHeaderId());
            poDtl.setPoNo(poNo);
            poDtl.setPoLineNo(ifPoDtl.getEbelp());
            poDtl.setFactory(ifPoDtl.getWerks());
            poDtl.setFmFactory(ifPoDtl.getRewek());
            poDtl.setSkuId(sku.getSkuId().longValue());
            poDtl.setOrderQty(ifPoDtl.getMenge());
            poDtl.setOrderQtyEa(ifPoDtl.getMenge());
            poDtl.setReturnPo(ifPoDtl.getRetpo());
            poDtl.setCompFlag(ifPoDtl.getElikz());
            poDtl.setDelFlag(ifPoDtl.getLoekz());

            poDtl.setLotAttr1("11sss");//待定

            if (poDtlRecord == null) {
                //TODO   待定
                poDtl.setStatus(1L);//新建
                poDtl.setUnit("单位");
                poDtl.setRcvQty(new BigDecimal(0));//待定
                try {
                    poDtl.setCreateTime(ifPoDtl.getCreateTime());
                    poDtl.setCreateUser(ifPoDtl.getCreateUser());
                    poDtlMapper.insert(poDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, poNo, e.getMessage());
                }
            } else {
                poDtl.setModifyUser("system");
                poDtl.setModifyTime(new Date());
                poDtl.setPoDtlId(poDtlRecord.getPoDtlId());
                try {
                    poDtlMapper.updateById(poDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, poNo, e.getMessage());
                }
            }
            int row = ifPoHeaderMapper.updateFlagById(data.getIfPoHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, poNo);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, poNo);
            }
        }

    }

}
